package com.addressbook.tests;

import static com.addressbook.tests.ContactDataGenerator.loadsContactsFromXmlFile;
//import static com.addressbook.tests.ContactDataGenerator.loadsContactsFromCsvFile;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.addressbook.fw.ContactData;
import com.addressbook.utils.SortedListOf;

public class ContactEditionTests extends TestBase {

	@DataProvider
    public static Iterator<Object[]> getValidContactFromFile() throws IOException {
            return wrapContactsForDataProvider(
            		loadsContactsFromXmlFile(new File("contacts.xml"))).iterator();
//    				loadsContactsFromCsvFile(new File("contacts.txt"))).iterator();            
    }
	
	@Test(dataProvider = "getValidContactFromFile")
	public void testContactEditionValidData(ContactData contact) {

		// save old
		SortedListOf<ContactData> oldstate = new SortedListOf<ContactData> (app.getHibernateHelper().listContacts());
		if (oldstate.size() == 0) throw new Error ("There is no contacts to Delete.");
		Random rnd = new Random();
		int index = rnd.nextInt(oldstate.size());		

		app.getContactHelper().editContract(index, contact);

		// save new
		SortedListOf<ContactData> newstate = app.getContactHelper().getContacts();

		// check
		for (ContactData contactData : oldstate) {
			contactData.correctionContact();
		}
		assertThat(newstate, equalTo(oldstate.without(index).withAdded(contact.correctionContact())));
	}
}
